<template>
  <div style="height: 600px;width: 100%;">
    <div style="height: 100px;width: 100%;">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>发票录入添加编辑</el-breadcrumb-item>
    </el-breadcrumb>
    </div>
    <div style="height: 300px;width: 100%;">
      <div style="height: 80%;width: 30%;float: left">
        <el-form label-width="120px" :model="DataForm" ref="DataForm" :rules="rules">
          <el-form-item label="主键" prop="id" v-show="false">
            <el-input size="small" v-model="DataForm.bid" auto-complete="off" placeholder="请输入主键"></el-input>
          </el-form-item>
          <el-form-item label="发票号" prop="billnum">
            <el-input size="small" v-model="DataForm.billnum" auto-complete="off" placeholder="请输入发票号"></el-input>
          </el-form-item>
          <el-form-item label="报销金额" prop="amount">
            <el-input size="small" v-model="DataForm.amount" auto-complete="off" placeholder="请输入报销金额"></el-input>
          </el-form-item>
          <el-form-item label="报销人" prop="baoxiaoname">
            <el-input size="small" v-model="DataForm.baoxiaoname" auto-complete="off" placeholder="请输入报销人"></el-input>
          </el-form-item>
          <el-form-item label="图片地址" prop="imageurl" v-show="false">
            <el-input size="small" v-model="DataForm.imageurl" auto-complete="off" placeholder="请输入图片地址"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
            <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('DataForm')">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="height: 80%;width: 2%;float: left">
      </div>
      <div style="height: 80%;width: 59%;float: left">
        <div style="height: 100%;width: 100%;margin: auto" v-if="imageUrl">
<!--          <imageUpload v-model="fileList" @dataFromChild="handleChildData" />-->
          <el-upload
            class="avatar-uploader"
            :action="uploadImgUrl"
            :on-success="handleSuccess"
            :on-remove="handleDelete"
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="1"
            :headers="headers"
            :auto-upload="true"
            :show-file-list="false"
          >
            <div class="avatar" v-if="imageUrl">
              <img :src="imageUrl" alt="Uploaded Image" class="image-preview">
            </div>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!-- 上传提示 -->
          <div class="el-upload__tip" slot="tip" v-if="showTip">
            请上传
            <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
            <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
            的文件
          </div>
        </div>
        <div v-else>
          <!--          <imageUpload v-model="fileList" @dataFromChild="handleChildData" />-->
          <el-upload
            class="avatar-upload"
            :action="uploadImgUrl"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="1"
            :headers="headers"
            :auto-upload="true"
            :show-file-list="false"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  ModelSave,
  getModelById,
  modelUpload, FapiaoSave, FapiaoUpdate
} from '../../api/userMG'
import imageUpload from "../../imageUpload/index.vue";

export default {
  components: {imageUpload},
  data() {
    return {
      fileList: [],
      fileContent: '',
      imageUrl:'',
      loading: false, //是显示加载
      DataForm: {
        bid:'',
        baoxiaoname:'',
        billnum:'',
        amount:'',
        imageurl:'',
      },
      // rules 表单验证
      rules: {
        baoxiaoname: [
          { required: true, message: '请输入报销人', trigger: 'blur' }
        ],
        billnum: [
          { required: true, message: '请输入发票号', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入报销金额', trigger: 'blur' }
        ],

      },
      baseUrl: "http://192.168.2.88:9990/photos",
      // baseUrl: "http://192.168.80.155:8788/photos",
      // uploadImgUrl: "http://127.0.0.1:9990/api/getocr/putfile", // 上传的图片服务器地址
      uploadImgUrl: "http://192.168.2.88:9990/api/getocr/putfile", // 上传的图片服务器地址
      headers: {
        token: localStorage.getItem('token'),
      },
    };
  },
  created() {
    this.DataForm.bid = this.$route.params.id;
    this.DataForm.baoxiaoname = this.$route.params.baoxiaoname;
    this.DataForm.billnum = this.$route.params.billnum;
    this.DataForm.amount = this.$route.params.amount;
    this.DataForm.imageurl = this.$route.params.imageurl;
    if(this.$route.params.imageurl != undefined && this.$route.params.imageurl != 'undefined'){
      this.imageUrl = this.baseUrl+this.$route.params.imageurl;
    }
    console.log(this.imageUrl)
  },

  methods: {
    closeDialog(obj){
      this.$router.push({ name: 'fapiao' });//跳转到查询界面
    },
    // handleChildData(dataFromChild) {
    //   // 父组件接收到子组件传递的数据
    //   this.DataForm.amount = dataFromChild.data.amount;
    //   this.DataForm.billnum = dataFromChild.data.billnum;
    // },
    // 编辑、增加保存方法
    submitForm(editData) {
      this.loading = true
      this.$refs[editData].validate(valid => {
        if (valid) {
          if(this.DataForm.bid != undefined && this.DataForm.bid != 'undefined'){
            FapiaoUpdate(this.DataForm)
              .then(res => {
                console.log(res.success)
                if(res.code==null){
                  this.$router.push({ name: 'login' });//跳转到查询界面
                }
                if (res.code===0) {
                  // this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '数据保存成功！'
                  })
                  this.$router.push({ name: 'fapiao' });//跳转到查询界面
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.$message.error('模型保存失败，请稍后再试！')
              })
          }else {
            FapiaoSave(this.DataForm)
              .then(res => {
                console.log(res.success)
                if(res.code==null){
                  this.$router.push({ name: 'login' });//跳转到查询界面
                }
                if (res.code===0) {
                  // this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '数据保存成功！'
                  })
                  this.$router.push({ name: 'fapiao' });//跳转到查询界面
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.$message.error('模型保存失败，请稍后再试！')
              })
          }
        } else {
          return false
        }
      })
      this.loading = false
    },
    handleSuccess(res, file) {
      if(res.code==null){
        this.$router.push({ name: 'login' });//跳转到查询界面
      }
      // 上传成功后的处理逻辑
      if (res.code === 0) {
        this.DataForm.amount = res.data.amount;
        this.DataForm.billnum = res.data.billnum;
        this.DataForm.imageurl = res.data.imageurl;
        this.fileList.push({ name: res.data.imageurl, url: res.data.imageurl });
        this.imageUrl = this.baseUrl+res.data.imageurl;
        console.log(this.imageUrl)
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除图片
    handleDelete(file) {
      this.imageUrl=null;
      // const findex = this.fileList.map(f => f.name).indexOf(file.name);
      // if (findex > -1) {
      //   this.fileList.splice(findex, 1);
      //   this.$emit("input", this.listToString(this.fileList));
      // }
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt500k = file.size / 1024 < 500;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt500k) {
        this.$message.error('上传图片大小不能超过 500KB!');
      }
      return isJPG || isPNG && isLt500k;
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
  }
};
</script>
<style scoped>
.avatar-upload {
  width: 100px; /* 你可以根据需要调整这个值 */
  height: 100px; /* 你可以根据需要调整这个值 */
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden; /* 隐藏超出容器的内容 */
  position: relative;
  cursor: pointer;
}
.avatar-uploader {
  width: 800px; /* 你可以根据需要调整这个值 */
  height: 600px; /* 你可以根据需要调整这个值 */
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden; /* 隐藏超出容器的内容 */
  position: relative;
  cursor: pointer;
}

.avatar {
  width: 800px;
  height: 600px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.image-preview {
  max-width: 800px; /* 图片最大宽度为容器宽度 */
  max-height: 600px; /* 图片最大高度为容器高度 */
  object-fit: cover; /* 保持图片比例，同时填充整个容器 */
}

.avatar-uploader-icon {
  font-size: 40px;
  color: #8c939d;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
